import React, { useState, useEffect, useMemo } from 'react';
import { history } from 'umi';
import { connect } from 'dva';
import { Tabs, Button } from 'antd';
import styles from './index.less';
import {
  getPageItemByPath,
  getPageItemById,
  getParentMenuByPage,
} from '@/utils/utils';

import KeepAlive, { useAliveController } from 'react-activation'; // 页面缓存

const SubNavLayout = (props) => {
  const { children, location, menuData } = props;
  const [tags, setTags] = useState(props.auditDetail.tags);

  // const { dropScope } = useAliveController();
  const [currentTag, setCurrentTag] = useState({});
  const [currentSubMenu, setCurrentSubMenu] = useState({});

  useEffect(() => {
    props.dispatch({
      type: 'auditDetail/changeTabs',
      payload: {
        tags,
        setTags,
        cleartag: [],
      },
    });
  }, [tags, setTags]);
  // 设置dva中过滤之后的tabs
  useEffect(() => {
    // setTags(props.auditDetail.tags)
    tagOptions.removeTag(props.auditDetail?.cleartag[0]?.id, 'pageClose');
  }, [children, tagOptions]);

  const tagOptions = useMemo(
    () => ({
      removeTag: (ids, type) => {
        let id = ids && Number(ids);
        if (id && currentTag.id === id) {
          // 点击close图标，清除"航延服务申请单"缓存数据
          if (currentTag.path?.indexOf('usualMonitor/AuditDetail') >= 0) {
            props.dispatch({
              type: 'auditDetail/resetUploadList',
            });
          }
          // 点击tab的关闭图表，才回退到上一个tab
          if (type === 'iconClose') {
            const nextIndex =
              [].findIndex.call(tags, (item) => item.id === id) - 1;
            tagOptions.clickTag(tags[nextIndex < 0 ? 1 : nextIndex]?.id);
          }
          // 解决关闭后重新打开的问题
          setTimeout(() => {
            setTags((tags) => tags.filter((item) => item.id !== id));
            // 解除已经关闭的tab页面的缓存
            // dropScope(currentTag.path);
          }, 0);
        } else {
          // 不在当前页面点击关闭,清除缓存
          let removeTagObj = tags.filter((item) => item.id === id);
          // dropScope(removeTagObj[0]?.path);
          setTags((tags) => tags.filter((item) => item.id !== id)); // 问题：id为空
        }
      },
      clickTag: (id) => {
        const current = getPageItemById(id, menuData);
        setCurrentTag(current);
        //递归遍历， 将路由数据取出来, 这个逻辑需要优化，
        const getName = (menuData) => {
          const result = [];
          menuData.forEach((item) => {
            const map = (data) => {
              const { id, path } = data;
              path && result.push({ id, path });
              data.children && data.children.forEach((child) => map(child));
            };
            map(item);
          });
          return result;
        };
        const pathObj = getName(menuData).find(
          (item) => item.id.toString() === id.toString(),
        );
        history.push(pathObj.path);
      },
      onPathChange(path) {
        if (path === currentTag.path) return; // 解决关闭后重复添加
        let current = {};
        current = getPageItemByPath(path, menuData);
        // console.log('current :>> ', current);
        // console.log('(path, menuData) :>> ', path, menuData);
        if (currentTag.type == '2') {
          sessionStorage.setItem('activeTag', path);
        }
        if (current.path) {
          if (
            current.path === path ||
            (current.containPath &&
              ~current.containPath.split(';').indexOf(path))
          ) {
            const subMenu = current.pid
              ? getParentMenuByPage(current, menuData)
              : {};
            setCurrentSubMenu(subMenu);
            const isInTags = tagOptions._isInTags(current.id, tags);
            if (!isInTags) {
              setTags((tags) => tags.concat([current]));
            } else {
              // 如果跳转的目标页面 存在于 tags 数组中， 就更新tags中航延补偿的路由对象。 以便于tags的标题更新
              if (
                current.path?.indexOf('usualMonitor/AuditDetail') >= 0 ||
                current.path === '/compensation/indemnityForm' ||
                current.path ===
                  '/compensation/CompensationAudit/AuditDetail' ||
                current.path === '/compensation/luggageLndemnifyDetails'
              ) {
                let tempTags = JSON.parse(JSON.stringify(tags));
                for (let item of tempTags) {
                  if (item.id === current.id) {
                    item.name = current.name;
                  }
                }
                setTags(tempTags);
              }
            }
            setCurrentTag(current);
          } else {
            history.push(current.path); // 如果当前路径是菜单路径，跳转到页面路径
          }
        }
      },
      _isInTags: (id, tags) => ![].every.call(tags, (item) => item.id !== id),
    }),
    [tags, setTags, menuData, currentTag],
  );

  useEffect(() => {
    // 解除页面缓存，避免不刷新的bug。
    // dropScope('/features/sysSetting/addEditClientele');
    // dropScope('/features/sysSetting/menuOperation');
    tagOptions.onPathChange(location.pathname);
  }, [location, tagOptions]);

  return (
    <div>
      <Tabs
        hideAdd
        size="small"
        onTabClick={tagOptions.clickTag}
        activeKey={currentTag.id}
        type={tags.length > 1 ? 'editable-card' : 'card'}
        onEdit={(target, action) => {
          action === 'remove' && tagOptions.removeTag(target, 'iconClose');
        }}
      >
        {tags.map((pane) => (
          <Tabs.TabPane
            tab={pane.name}
            key={pane.id}
            style={{ display: 'none' }}
          ></Tabs.TabPane>
        ))}
      </Tabs>
      {/* <KeepAlive
        id={children?.props?.location?.pathname}
        name={children?.props?.location?.pathname}
      > */}
      <div style={{ margin: '0px 16px', minHeight: 'calc(100vh - 100px)' }}>
        {children}
      </div>
      {/* </KeepAlive> */}
    </div>
  );
};

export default connect(({ auditDetail }) => ({
  auditDetail,
}))(SubNavLayout);
